/*
** File:   mainwindow.cpp
** Class:  
** Author: Krzysztof Sas
** Date:   2012-03-29
******************************/

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent), m_port(13)
{
    m_udpSocket = new QUdpSocket(this);
    m_udpSocket->connect(m_udpSocket,SIGNAL(readyRead()),this,
                         SLOT(onClientRecv()));

    m_textEdit = new QLineEdit;
    m_received = new QTextEdit;

    m_send = new QToolButton;
    m_send->setText("send");
    connect(m_send,SIGNAL(clicked()),this,SLOT(sendMessage()));

    m_udpSocket->connectToHost(QHostAddress::LocalHost,13);

    QGridLayout *aLay = new QGridLayout;
    aLay->addWidget(m_textEdit);
    aLay->addWidget(m_received);
    aLay->addWidget(m_send);


    //connect(&m_timer,SIGNAL(timeout()),this,SLOT(checkState()));
    //m_timer.start(500);


    setLayout(aLay);
}

MainWindow::~MainWindow()
{

}

void MainWindow::checkState()
{
    QByteArray check = "check";
    m_udpSocket->writeDatagram(check,QHostAddress::LocalHost,m_port);
}

void MainWindow::onClientRecv()
{
    while(m_udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(m_udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        m_udpSocket->readDatagram(datagram.data(),datagram.size(),&sender,
                                  &senderPort);
        QDateTime dt = QDateTime::currentDateTime();
        QString sDtString = dt.toString("yyyy-MM-dd HH:mm:ss");
        QString sLog = sDtString + ":" + QString::fromUtf8(datagram) + "\n" ;
        m_received->append(sLog);
        //m_udpSocket->writeDatagram(datagram,sender,senderPort);
    }
}

void MainWindow::sendMessage()
{
    QString sSendMsg = m_textEdit->text();
    m_udpSocket->writeDatagram(sSendMsg.toUtf8(),
                               QHostAddress::LocalHost,m_port);
}
